import { createRouter, createWebHistory } from "vue-router";
import { getToken } from "../utils/common";
import store from "@/store";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/",
      name: "index",
      component: () => import("@/pages/layout/index.vue"),
      children: [
        {
          path: "/examples/test1",
          // name: "examples_test1",
          component: () => import("@/pages/examples/test1/index.vue"),
        },
        {
          path: "/examples/test2",
          component: () => import("@/pages/examples/test2/index.vue"),
        },
        {
          path: "/sys/user",
          name: "sys_user",
          component: () => import("@/pages/sys/user/index.vue"),
        },
        {
          path: "/sys/menu",
          name: "sys_menu",
          component: () => import("@/pages/sys/menu/index.vue"),
        },
        {
          path: "/sys/role",
          name: "sys_role",
          component: () => import("@/pages/sys/role/index.vue"),
        },
      ],
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/pages/login/index.vue"),
    },
  ],
});

// 全局前置守卫
router.beforeEach((to) => {
  if (to.name !== "login") {
    // 获取token
    const token = getToken();
    // 没有token,跳转至登录页
    if (!token) {
      return {
        name: "login",
        query: {
          redirect: to.fullPath,
        },
      };
    }
    if (!store.state.user.person) {
      // 获取个人信息
      //   store.dispatch("user/getPerson");
      //   store.dispatch("user/getPermmenu");
      // 优化过后的(两者结合调用)
      store.dispatch("user/get").then((res) => {
        // console.log('res', res);
      });
    }
  }
});
export default router;
